#include "Logger.h"
#include <iostream>
#include <fstream>
#include <chrono>
#include <ctime>
#include <cstdarg>

// 构造函数：打开日志文件
Logger::Logger(const std::string& filename) : logFile(filename, std::ios::trunc) {
    if (!logFile.is_open()) {
        std::cerr << "Failed to open log file: " << filename << std::endl;
    }
}

// 析构函数：关闭日志文件
Logger::~Logger() {
    if (logFile.is_open()) {
        logFile.close();
    }
}

// 获取当前时间戳
std::string Logger::getTimestamp() const {
    auto now = std::chrono::system_clock::now();
    auto timePoint = std::chrono::system_clock::to_time_t(now);

    std::tm tm = *std::localtime(&timePoint);
    std::ostringstream timestampStream;
    timestampStream << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");

    return timestampStream.str();
}

// 写入简单日志（单行）
void Logger::log(const std::string& message) {
    if (logFile.is_open()) {
        logFile << getTimestamp() << " - " << message << std::endl;
    }
}

// 写入格式化日志
void Logger::logFormatted(const std::string& format, ...) {
    if (logFile.is_open()) {
        va_list args;
        va_start(args, format);

        // 创建一个临时字符串来格式化日志
        char buffer[1024];
        vsnprintf(buffer, sizeof(buffer), format.c_str(), args);

        va_end(args);

        logFile << getTimestamp() << " - " << buffer << std::endl;
    }
}
